<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>抽象操作的标准流程</title>
</head>
<body>
    <h1>抽象操作的标准流程</h1>

    <script>
        // ToPrimitive 抽象操作
        const obj = {
            [Symbol.toPrimitive](hint) {
                switch (hint) {
                    case 'number':
                        return 123;
                    case 'string':
                        return 'str';
                    case 'default':
                        return 'default';
                }
            }
        };

        console.log(+obj);     // 123
        console.log(`${obj}`); // 'str'
        console.log(obj + ''); // 'default'

        // ToString 抽象操作
        console.log(String(null));      // 'null'
        console.log(String(undefined)); // 'undefined'
        console.log(String(true));      // 'true'
        console.log(String(3.14));      // '3.14'

        // ToNumber 抽象操作
        console.log(Number('123'));     // 123
        console.log(Number('12.34'));   // 12.34
        console.log(Number(''));        // 0
        console.log(Number(true));      // 1
        console.log(Number(false));     // 0
        console.log(Number(null));      // 0
        console.log(Number(undefined)); // NaN

        // ToBoolean 抽象操作
        console.log(Boolean(undefined)); // false
        console.log(Boolean(null));     // false
        console.log(Boolean(0));        // false
        console.log(Boolean(NaN));      // false
        console.log(Boolean(''));       // false
        console.log(Boolean({}));       // true
        console.log(Boolean([]));       // true

        // ToObject 抽象操作
        const str = Object('hello');
        console.log(typeof str);        // 'object'
        console.log(str instanceof String); // true

        // IsPropertyKey 抽象操作
        const sym = Symbol('foo');
        console.log(typeof sym === 'symbol'); // true
    </script>
</body>
</html>  